﻿using System.Runtime.InteropServices;
using System.Security;

namespace HDM.NexusEngine.Core
{
    public class PreciseTimer
    {
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Kernel32")]
        private static extern bool QueryPerformanceFrequency(out long lpPerformanceFreq);

        [SuppressUnmanagedCodeSecurity]
        [DllImport("Kernel32")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        private readonly long _ticksPerSecond;
        private long _previousElapsedTime;

        public PreciseTimer()
        {
            QueryPerformanceFrequency(out _ticksPerSecond);
            GetElapsedTime(); // Get rid of first rubbish result
        }

        public double GetElapsedTime()
        {
            long time;
            QueryPerformanceCounter(out time);
            double elapsedTime = (time - _previousElapsedTime) / (double)_ticksPerSecond;
            _previousElapsedTime = time;
            return elapsedTime;
        }
    }
}
